﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Cms.Core.Application.IService.RoleInfo;
using Cms.Core.Infrastructure.Dependency;
using Cms.Core.Infrastructure.Extension;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Linq;
using Microsoft.Extensions.Caching.Distributed;
using Cms.Core.Application.Secutiry.Token;
using Microsoft.Extensions.DependencyInjection;

namespace Cms.Core.Application.Secutiry.AuthHelper
{
    /// <summary>
    /// 
    /// </summary>
  public  class CmsJwtSecurityTokenHandler: JwtSecurityTokenHandler
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtToken"></param>
        /// <param name="issuer"></param>
        /// <param name="validationParameters"></param>
        /// <returns></returns>
        protected override ClaimsIdentity CreateClaimsIdentity(JwtSecurityToken jwtToken, string issuer, TokenValidationParameters validationParameters)
        {
            ClaimsIdentity identity=   base.CreateClaimsIdentity(jwtToken, issuer, validationParameters);
            bool isAdmin = false;
            if (identity.IsAuthenticated)
            {

               
                string token = jwtToken.RawData;
                DateTime exp = identity.GetExpiration<DateTime>();
                var scopedProvider = ServiceLocator.Instance.ScopedProvider;
                scopedProvider.ExecuteScopedWork(provider => {

                    var onlineUserCache = provider.GetService<IOnlineUserCache>();
                    var user = onlineUserCache.GetOrRefresh(identity.GetUserName());
                    isAdmin = user.IsAdmin;
                    //var onlineTokenCache = provider.GetService<IOnlineTokenCache>();
                    //var onlineToken = onlineTokenCache.GetOrRefresh(identity.GetUesrId<Guid>(), token, exp);
                });

            }

            ScopedDictionary dict = ServiceLocator.Instance.GetService<ScopedDictionary>();
            dict.Identity = identity;
            dict.IsAdmin = isAdmin;
            return identity;
        }

        protected override void ValidateLifetime(DateTime? notBefore, DateTime? expires, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
        {
            try
            {
                base.ValidateLifetime(notBefore, expires, jwtToken, validationParameters);
            }
            catch (Exception ex)
            {
                //var onlineTokenCache = ServiceLocator.Instance.GetService<IOnlineTokenCache>();

                // onlineTokenCache.Remove(jwtToken.RawData); ;
                throw;
            }
        }
    }
}
